package com.jt.deepSeaMain;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.config.TimingConfig;
import com.jt.controller.DeepSeaHttpController;
import com.jt.dto.CollectParamsDto;
import com.jt.mapper.TimingMapper;
import com.jt.pojo.*;
import com.jt.service.CarService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
@Slf4j
public class DeepCarTaskService extends TimingConfig {


    @Value("${task.car.switch}")
    private Boolean carSwitch;

    @Value("${task.car.cron}")
    private String carCron;

    @Value("${task.car.startTime}")
    private String startTime;


    @Autowired
    private TimingMapper timingMapper;

    @Autowired
    private DeepSeaHttpController deepSeaHttpController;

    private CarService carService;


    @Override
    protected Boolean getSwitch() {
        return carSwitch;
    }

    @Override
    protected String getCron() {
//        return "0 0/1 * * * ?";
        return carCron;
    }

    @Override
    protected void processTask() throws IOException {
        try {
            log.info("<<<<<<<<<<<<<<<<<start车脸定时任务>>>>>>>");
            //2:车辆car
            CollectParamsDto collectParamsDtoCar = new CollectParamsDto();
            collectParamsDtoCar.setPage(1);
            collectParamsDtoCar.setPageSize(100);
            collectParamsDtoCar.setSourceId("10174,7115");
            collectParamsDtoCar.setTargetType("car");
            collectParamsDtoCar.setRelative("face");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String systemTime = sdf.format(new Date());
            if (systemTime.compareTo(startTime) < 0) {
                log.error("车辆定时器执行时间小于系统默认开始时间");
                throw new RuntimeException("车辆定时器执行时间小于系统默认开始时间");
            } else {
                getCarCollectListAndSaveAll(startTime, systemTime, collectParamsDtoCar);
            }
        } catch (Exception e) {
            log.error(e.toString());
        }
    }

    /*统一去存入定时任务的开始结束和状态以及人抓入库和定时器时间入库*/
    public void getCarCollectListAndSaveAll(String startTime, String systemTime, CollectParamsDto collectParamsDtoCar) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<Car> CarList = null;
        try {
            List<String> timeList = new ArrayList<>();
            List<Timing> timings = timingMapper.selectList(null);
            /*如果定时器中没有数据，是第一次查，我们就取全局设定的开始时间*/
            if (CollectionUtils.isEmpty(timings)) {
                timeList.add(startTime);
                /*结束时间，拿到系统前一分钟时间*/
                String endTime = getCarBeForTime(systemTime);
                timeList.add(endTime);
                collectParamsDtoCar.setTimeList(timeList);
                /*定时任务开始之前存库一次*/
                Timing timing = new Timing();
                timing.setId(UUID.randomUUID().toString().substring(10));
                timing.setState("0");/*0开始，1执行中，2异常,3完成*/
                /*第一次调用采集接口*/
                Result result = deepSeaHttpController.getCollectList(collectParamsDtoCar);
                //存库调用统一方法:
                savePeopleAndPeoplePass(result, collectParamsDtoCar);
            } else {
                /*拿到定时器表中最后插入的时间*/
                Timing timing = timingMapper.selectOne(new QueryWrapper<Timing>().eq("type", "car").orderByDesc("end_time").last("limit 1"));
                String end_time = timing.getEndTime();
                timeList.add(end_time);
                /*结束时间，拿到系统前一分钟时间*/
                String before2Time = getCarBeForTime(systemTime);
                timeList.add(before2Time);
                collectParamsDtoCar.setTimeList(timeList);
                System.out.println("collectParamsDtoFace==" + collectParamsDtoCar);
                /*调用采集接口*/
                Result result = deepSeaHttpController.getCollectList(collectParamsDtoCar);
                log.info("collectList接口返回值==={}", result);
                savePeopleAndPeoplePass(result, collectParamsDtoCar);
            }
        } catch (Exception e) {
            log.error(e.toString());
        }

    }

    /*保存人脸和人体数据*/
    private void savePeopleAndPeoplePass(Result result, CollectParamsDto collectParamsDtoFace) {
        List<Car> peopleList = null;
        List<Car> peoplePassList = null;
        List<Car> newPeopleList = new ArrayList<>();
        List<Car> newPeoplePassList = new ArrayList<>();
        try {
            String res = result.getData().toString();
            JSONObject jsonObject = JSON.parseObject(res);
            /*人脸数据*/
            String faces = jsonObject.get("faces").toString();
            peopleList = JSON.parseArray(faces, Car.class);
            peopleList.forEach(onePeople -> {
                onePeople.setId(UUID.randomUUID().toString().substring(9));
                newPeopleList.add(onePeople);
            });
            boolean isAndTruePeople = carService.saveBatch(newPeopleList);
            if (!isAndTruePeople) {
                log.error("人脸数据保存失败");
            } else {
                log.info("人脸数据保存成功");
            }
            /*人体数据*/
            String bodies = jsonObject.get("bodies").toString();
            peoplePassList = JSON.parseArray(bodies, Car.class);
            peoplePassList.forEach(PeoplePass -> {
                PeoplePass.setId(UUID.randomUUID().toString());
                newPeoplePassList.add(PeoplePass);
            });
            boolean isAndTruePeoplePass = carService.saveBatch(newPeoplePassList);
            if (!isAndTruePeoplePass) {
                log.error("人体数据保存失败");
            } else {
                log.info("人体数据保存成功");
            }
            /*如果人脸和人体都保存成功了再去保存定时任务，反之会重新执行这个时间段的定时任务*/
            if (isAndTruePeople && isAndTruePeoplePass) {
                Timing timing = new Timing();
                timing.setId(UUID.randomUUID().toString().substring(10));
                List<String> timeList = collectParamsDtoFace.getTimeList();
                timing.setStartTime(timeList.get(0));
                timing.setEndTime(timeList.get(1));
                timing.setType(collectParamsDtoFace.getTargetType());
                timingMapper.insert(timing);
            }
        } catch (Exception e) {
            log.error("savePeopleAndPeoplePass方法中存库异常为:{}", e.toString());
            e.printStackTrace();
        }
    }

    public String getCarBeForTime(String systemTime) {
        String resultTime = "";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 将传入进来的时间转化为"yyyy-MM-dd HH:mm:ss"格式（格式可根据实际情况更改）
            Date startTime = sdf.parse(systemTime);
            System.out.println("系统时间==" + systemTime);
            // 将传入进来的时间转化为时间戳 ，然后再当前时间戳上减60000ms（1min=60000ms）
            long endTimeStamp = startTime.getTime() - 60000 * 2;
            // 转化计算得到的时间戳
            String endDateTemp = sdf.format(endTimeStamp);
            Date endTime = sdf.parse(endDateTemp);
            resultTime = sdf.format(endTime);
        } catch (Exception e) {
            log.error("获取系统前一分钟时间异常");
            e.printStackTrace();
        }
        return resultTime;
    }
}
